import 'package:base_lib/common/base/base_theme_state.dart';
import 'package:base_lib/config.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/repository/http.dart';
import 'package:doctor_order_lib/component.dart';
import 'package:doctor_order_lib/repository/order_http.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as LoginBean;
import 'entity/prescription_order_list_entity.dart' as OrderListBean;

///处方订单
class PrescriptionOrderListPage extends StatefulWidget {
  final Parameters parameters;

  PrescriptionOrderListPage(this.parameters);

  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends BaseThemeState {
  bool isRefresh = true;

  List<OrderListBean.Datas> currentData;

  OrderListBean.PageInfo _pageInfo =
      OrderListBean.PageInfo(pageIndex: 0, pageSize: 10);

  List<OrderListBean.Datas> itemList = [];

  RefreshController _refreshController;

  var doctorID;

  LoginBean.DoctorUser doctorUser;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController();

    UserInfoCache.getInstance().get().then((value) {
      doctorUser = value;
      doctorID = doctorUser.keyID;
      getNetList(getCurrentYearAndMonth());
    });
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  var tsBlackBig =
      TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold);
  var tsBlack = TextStyle(color: Colors.black, fontSize: 14);
  var tsGrey = TextStyle(color: Colors.grey, fontSize: 12);
  var tsRedBig =
      TextStyle(color: Colors.red, fontSize: 14, fontWeight: FontWeight.bold);
  var tsRed = TextStyle(color: Colors.red, fontSize: 14);

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      backgroundColor: theme.themeColor.themeBgColor,
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
        centerTitle: true,
        title: Text('处方订单'),
      ),
      body: Container(
        child: isRefresh
            ? buildLoadingIndicator()
            : itemList.isEmpty
                ? GestureDetector(
                    onTap: () {
                      isRefresh = true;
                      _pageInfo.pageIndex = 0;
                      getNetList(getCurrentYearAndMonth());
                      setState(() {});
                    },
                    child: buildPageEmpty())
                : SmartRefresher(
                    onRefresh: () {
                      isRefresh = true;
                      _pageInfo.pageIndex = 0;
                      return getNetList(getCurrentYearAndMonth());
                    },
                    onLoading: () {
                      return getNetList(_pageInfo.date);
                    },
                    controller: _refreshController,
                    enablePullUp: true,
                    child: ListView.builder(
                        itemCount: itemList.length,
                        itemBuilder: (context, pos) {
                          var item = itemList[pos];
                          return _buildItem(item, pos, theme);
                        }),
                  ),
      ),
    );
  }

  GestureDetector _buildItem(OrderListBean.Datas item, int pos, MTheme theme) {
    return GestureDetector(
      onTap: () {
        Routers.navigateTo(
            context, DoctorOrderComponent.prescriptionOrderDetailPage,
            parameters: Parameters()..putObj('item', item));
      },
      child: Container(
        margin: EdgeInsets.all(10),
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(15),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                10.hGapDp,
                ClipRRect(
                  borderRadius: BorderRadius.circular(15),
                  child: FadeInImage.assetNetwork(
                      placeholder:
                          'packages/${DoctorOrderComponent.AssetPackageName}/images/user_header.png',
                      width: 30,
                      height: 30,
                      image: item.faceImg ?? ''),
                ),
                5.hGapDp,
                Text('${item.personName}', style: tsBlackBig),
                5.hGapDp,
                Image.asset(
                  item.rpTypeID == 0 ? 'images/xy.png' : 'images/zy.png',
                  package: DoctorOrderComponent.AssetPackageName,
                  width: 25,
                  height: 25,
                ),
                Spacer(),
                Text(
                  '${item.orderStatusName}',
                  style: item.orderStatusID == 0 ? tsRed : tsBlack,
                ),
                10.hGapDp,
              ],
            ),
            10.vGapDp,
            DottedLine(color: Colors.grey[200], dashWidth: 2),
            10.vGapDp,
            Row(
              children: [
                10.hGapDp,
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                        '${item.patientName ?? '未知'}  ${Utils.returnGenderByInt(item.patientSex)}  ${item.patientAge ?? '未知'}岁'),
                    5.vGapDp,
                    Text(
                      '诊断：${item.primaryDiagnosis ?? '未知'}',
                      style: tsGrey,
                    )
                  ],
                )),
                Text(
                  '¥${Config.formatMoney(item.orderPrice)}',
                  style: tsRedBig,
                ),
                10.hGapDp,
              ],
            ),
            15.vGapDp,
            Padding(
              padding: EdgeInsets.only(left: 10),
              child: Text(
                '${item.createTime}',
                style: tsGrey,
              ),
            ),
            10.vGapDp,
          ],
        ),
      ),
    );
  }

  String getCurrentYearAndMonth() {
    var now = new DateTime.now();
    return DateUtil.formatDate(now, format: DateFormats.y_mo);
  }

  getNetList(date) async {
    var result = await DoctorOrderHttp.getPrescriptionOrder(
        _pageInfo.pageIndex + 1, doctorID, date);
    if (result.isSuccess) {
      currentData = result.data.datas;
      _pageInfo.date = result.data.pageInfo.date;
      _pageInfo.pageIndex = result.data.pageInfo.pageIndex;
      _pageInfo.totalPage = result.data.pageInfo.totalPage;

      if (_pageInfo.pageIndex < 0) {
        _refreshController.loadNoData();
        isRefresh = false;
        itemList.clear();
        doRefresh();
        return;
      }

      if (result.data.datas.isEmpty) {
        getNetList(_pageInfo.date);
        return;
      }

      if (isRefresh) {
        itemList.clear();
        isRefresh = false;
      }
      getHeaders(currentData);
    } else {
      ToastUtil.error(result.error.msg);
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
      isRefresh = false;
      doRefresh();
    }
  }

  void getHeaders(List<OrderListBean.Datas> datas) async {
    _refreshController.refreshCompleted();
    _refreshController.loadComplete();

    List<OrderListBean.Datas> realList = [];
    realList.addAll(datas);

    var ids = '';
    realList.forEach((element) {
      ids += '${element.personID},';
    });

    var result = await DoctorOrderHttp.getUserHeadersByIDs(ids);
    if (result.isSuccess) {
      realList.forEach((element) {
        result.data.forEach((image) {
          if (element.personID == image.keyID) {
            element.faceImg = image.faceImage;
          }
        });
      });

      currentData = realList;
      itemList.addAll(realList);
      doRefresh();
    } else {
      ToastUtil.error(result.error.msg);
    }
  }

  void doRefresh() {
    setState(() {});
  }
}
